<%@page import="avicit.cbb.techclass.tabledefine.sysstandardfunction.service.SysStandardFunctionService"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="java.util.Map.Entry"%>
<%@page import="java.util.ArrayList"%>
<%@page import="avicit.cbb.techclass.tabledefine.commtablemanager.domain.CbbTabColumns"%>
<%@page import="avicit.cbb.techclass.tabledefine.commtablemanager.action.service.CommTableManagerService"%>
<%@page import="avicit.platform6.api.sysuser.dto.SysOrg"%>
<%@page import="avicit.platform6.api.sysuser.SysOrgAPI"%>
<%@page import="avicit.im.lantop.userauthset.service.UserAuthIntfsService"%>
<%@page import="avicit.cbb.billdefine.service.BillDefineManagerIntfsService"%>
<%@page import="avicit.im.lantop.archiveclassmanager.service.ArchiveClassManagerIntfsService"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Map"%>
<%@page import="avicit.platform6.api.session.SessionHelper"%>
<%@page import="avicit.platform6.core.spring.SpringFactory"%>
<%@page import="avicit.cbb.tabledefine.service.CommTableManagerIntfsService"%>
<%@page import="avicit.platform6.api.sysshirolog.impl.AfterLoginSessionProcess"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%
	boolean isAddOrEdit=true;
	String dialogId = request.getParameter("dialogId");//对话框ID用于判断是否是添加页面
	String nodeId = request.getParameter("nodeId");// 档案分类树ID
	String id = request.getParameter("id");
	String archivesId = request.getParameter("archivesId"); // 案卷文件著录有值
	archivesId = archivesId==null?"":archivesId;
	String dataSecret = request.getParameter("dataSecret");
	if(dialogId==null || (!dialogId.contains("Add") && !dialogId.contains("Edit"))){
		isAddOrEdit = false;
		//不是否添加或删除页面
		return ;
	}
	//if(isAddOrEdit){return;}
	
	System.out.println("Start apply_gene_rule:"+new java.util.Date());
	CommTableManagerIntfsService commTableManagerIntfsService = SpringFactory.getBean(CommTableManagerIntfsService.class);
	ArchiveClassManagerIntfsService	archiveClassManagerIntfsService = SpringFactory.getBean(ArchiveClassManagerIntfsService.class);
	BillDefineManagerIntfsService billDefineManagerIntfsService = SpringFactory.getBean(BillDefineManagerIntfsService.class);
	UserAuthIntfsService userAuthIntfsService = SpringFactory.getBean(UserAuthIntfsService.class);
	//SysOrgAPI sysOrgAPI = SpringFactory.getBean(SysOrgAPI.class);
	CommTableManagerService commTableManagerService = SpringFactory.getBean(CommTableManagerService.class);
	SysStandardFunctionService sysStandardFunctionService = SpringFactory.getBean(SysStandardFunctionService.class);
	
	Object sessionLanguageCode = request.getSession().getAttribute(AfterLoginSessionProcess.SESSION_CURRENT_LANGUAGE_CODE);
	String sysId = "LANTOP";
	String userId = SessionHelper.getLoginSysUserId(request);
	String orgId = SessionHelper.getCurrentOrgId(request);
	String deptId = SessionHelper.getCurrentDeptId(request);
	//String orgIdentity = SessionHelper.getCurrentOrgIdentity(request);
	//SysOrg so = sysOrgAPI.getSysOrgBySysOrgId(orgIdentity);
	//String orgCode = so.getOrgCode();
	
	//edit by zhangjq 2020-5-3 13:36 修改为从java的action里传递，优化页面加载速度
	//List<Map<String, Object>> treeNodeIdList = commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(orgId, deptId, sysId, nodeId, "");
	List<Map<String, Object>> treeNodeIdList = (List<Map<String, Object>>)request.getAttribute("treeNodeIdList");
	//end edit
	
	String tableId = "";
	String tableName = "";
	String ajTableName="";
	String ajTableId="";
	int tableCount=1;
//	Map<String, Object> param = new HashMap<String, Object>();
//	param.put("currentUserId", userId);
//	param.put("currentDeptId", deptId);
//	param.put("currentOrgCode", orgCode);
//	param.put("languageCode", sessionLanguageCode);
	
	//获取案卷级字段值方法的参数
	Map<String, Object> paramGetAjColVal = new HashMap<String, Object>();
	paramGetAjColVal.put("languageCode", sessionLanguageCode);
	paramGetAjColVal.put("nodeId", nodeId);
	paramGetAjColVal.put("orgId", orgId);
	paramGetAjColVal.put("deptId", deptId);
	paramGetAjColVal.put("sysId", sysId);
	
	String mapApplyColRuleJsonStr="{}";
	String colRuleListJsonStr="[]";
	String setColRuleListJsonStr="[]";
	
	//获取表名
	if (null != treeNodeIdList && treeNodeIdList.size() > 0) {
		Map<String, Object> modelParam = new HashMap<String, Object>();
		modelParam.put("treeNodeList", treeNodeIdList);
		Map<String, Object> modelMap = archiveClassManagerIntfsService.getDataNodeInfoByParam(modelParam);
		int dataCount = Integer.parseInt(modelMap.get("dataCount").toString());
		tableCount=treeNodeIdList.size();
		if (tableCount == 1 || dataCount == 1) { // 加载文件记录
			tableId = (String) treeNodeIdList.get(0).get("ID");
			tableName = (String) treeNodeIdList.get(0).get("TABLE_NAME");
		} else {
			tableId = (String) treeNodeIdList.get(1).get("ID");
			tableName = (String) treeNodeIdList.get(1).get("TABLE_NAME");
			//获取案卷表名
			ajTableId = (String) treeNodeIdList.get(0).get("ID");
			ajTableName = (String) treeNodeIdList.get(0).get("TABLE_NAME");
		}
		
		//edit by zhangjq 2020-5-3 13:36 修改为从java的action里传递，优化页面加载速度
//		/***** 2015/07/27增加-郭亮-拼接条件sql *****/
//		String sql = " AND NODE_ID = '" + nodeId + "' AND (ARCHIVE_STATUS = '1' OR ARCHIVE_STATUS IS NULL OR ARCHIVE_STATUS = '')";// 模块固定条件sql
//		if (null == archivesId || "".equals(archivesId) || "null".equals(archivesId)) { // 案卷ID为空(待整理文件)
//			sql = sql + " AND (PARENT_ID IS NULL OR PARENT_ID = '')";
//		} else { // 案卷ID不为空(案卷下的文件)
//			sql = sql + " AND PARENT_ID = '" + archivesId + "'";
//		}
//		Map<String, Object> secretParam = new HashMap<String, Object>();
//		secretParam.put("orgIdentity", SessionHelper.getCurrentOrgIdentity(request));
//		Map<String, String> userAuthMap = userAuthIntfsService.getUserAuthDatasByIntfs(orgId, deptId, sysId, "3", userId, "LANTOP_AUTH_SERVER_USERSET", nodeId, tableId, "", secretParam);// 权限Map
//		String userAuthsql = userAuthMap.get("SQL");// 权限sql
//		sql = sql + userAuthsql;// 最终条件sql
//		param.put("userAuthsql", sql);
//		param.put("nodeId", nodeId);
//		if (null != archivesId && !"".equals(archivesId) && !"null".equals(archivesId)) {
//			Map<String, Object> parentMap = new HashMap<String, Object>();
//			parentMap.put("dataId", archivesId);
//			param.put("parentDataId", archivesId);
//			param.put("ortherMap", parentMap);
//		} else {
//			// 判断是否有父级数据,如果没有,则添加父级密级为max,文件添加时则不进行父级数据和子级数据的密级验证
//			dataSecret = "max";
//		}
//		/***** 2015/07/27增加-郭亮-拼接条件sql *****/
//		List<Map<String, Object>> addForm = billDefineManagerIntfsService.getFieldsByConditionByIntfs(orgId, deptId, sysId, tableId, "1", id, param); // 添加区域
		List<Map<String, Object>> addForm = (List<Map<String, Object>>)request.getAttribute("editFrom");
		if (addForm==null) addForm = (List<Map<String, Object>>)request.getAttribute("addFrom");
		//end edit
		
		//转换JS执行
		List<Map<String, Object>> mapAjCols = null;
		if(tableCount>1){
			try{
			mapAjCols = sysStandardFunctionService.getColumnsByTableId(ajTableId);
			}catch(Exception ex){}
		}
		Map<String, List<Integer>> mapApplyColRule = new HashMap<String, List<Integer>>();
		List<String> colRuleList = new ArrayList<String>();
		List<String> setColRuleList = new ArrayList<String>();
		
		String replaceColName="";
		int ruleColCount=0;
		for(Map<String, Object> mapCol:addForm){
			String colId = mapCol.get("ID")+"";
			String colName = mapCol.get("COL_NAME")+"".toUpperCase();
			String colRuleName = mapCol.get("COL_RULE_NAME")==null?"":mapCol.get("COL_RULE_NAME")+"";
			String dropType = mapCol.get("COL_DROPDOWN_TYPE")==null?"":mapCol.get("COL_DROPDOWN_TYPE")+"";
			String colType = mapCol.get("COL_TYPE")+"";
			CbbTabColumns cbbTabcolumns = commTableManagerService.getCbbTabColumnsById(colId);
			//mapCols.put(cbbTabcolumns.getColName(), cbbTabcolumns);
			String colGeneMethodRule = cbbTabcolumns.getColGeneMethodRule();
			String colGeneMethodRuleText = cbbTabcolumns.getColGeneMethodRuleText();//组合项设置胡中文显示
			if(null != colGeneMethodRule && colGeneMethodRuleText!=null && !colGeneMethodRuleText.isEmpty()){
				//处理当前表的字段
				for(Map<String, Object> mapColReplace:addForm){
					String currColName = mapColReplace.get("COL_NAME")+"".toUpperCase();
					String currColRuleName = mapColReplace.get("COL_RULE_NAME")==null?"":mapColReplace.get("COL_RULE_NAME")+"";
					String currDropType = mapColReplace.get("COL_DROPDOWN_TYPE")==null?"":mapColReplace.get("COL_DROPDOWN_TYPE")+"";
					String currColType = mapColReplace.get("COL_TYPE")+"";
					//replaceColName=tableCount>1?tableName.toUpperCase()+"."+currColName:currColName;
					replaceColName=tableName.toUpperCase()+"."+currColName;
					if(colGeneMethodRule.contains(replaceColName)){
						colGeneMethodRule = colGeneMethodRule.replace(replaceColName, "getColVal('"+currColName+"','"+currDropType+"','"+currColRuleName+"','"+currColType+"')");
						List<Integer> listRuleIndexs = null;
						if(mapApplyColRule.get(currColName)==null){
							listRuleIndexs = new ArrayList<Integer>();
							mapApplyColRule.put(currColName, listRuleIndexs);
						}else{
							listRuleIndexs = (List<Integer>)mapApplyColRule.get(currColName);
						}
						listRuleIndexs.add(ruleColCount);
					}
				}
				
				//add by zhangjq 20200-5-3 如果没设置其他字段生成的时候的处理，将自身加入到规则之中
				if(mapApplyColRule.get(colName)==null){
					List<Integer> listRuleIndexs = new ArrayList<Integer>();
					mapApplyColRule.put(colName, listRuleIndexs);
					listRuleIndexs.add(ruleColCount);
				}
				//end add
				
				//处理在案卷级表的字段
				if(tableCount>1 && mapAjCols!=null 
					//add by zhangjq 2020-5-3 14:03 只有存在案卷级字段时，才执行案卷级字段的循环，用于页面加载速度
					&& colGeneMethodRule.toUpperCase().contains(ajTableName.toUpperCase()+".")){
					//end add
					for(Map<String, Object> mapColReplace:mapAjCols){
						String currColId =mapColReplace.get("ID")+"";
						String currColName = mapColReplace.get("COL_NAME")+"".toUpperCase();
						String currColRuleName = mapColReplace.get("COL_RULE_NAME")==null?"":mapColReplace.get("COL_RULE_NAME")+"";
						String currDropType = mapColReplace.get("COL_DROPDOWN_TYPE")==null?"":mapColReplace.get("COL_DROPDOWN_TYPE")+"";
						String currColType = mapColReplace.get("COL_TYPE")+"";
						replaceColName=ajTableName.toUpperCase()+"."+currColName;
						if(colGeneMethodRule.contains(replaceColName)){//是案卷字段时，直接将字段替换为具体的值
							String ajColVal=sysStandardFunctionService.getAjColValue(currColId, ajTableName, ajTableId, archivesId, paramGetAjColVal);
							colGeneMethodRule = colGeneMethodRule.replace(replaceColName, "'"+ajColVal+"'");
							//colGeneMethodRule = colGeneMethodRule.replace(replaceColName, "getAjColVal('"+archivesId+"','"+currColId+"','"+currColName+"','"+currDropType+"','"+currColRuleName+"','"+currColType+"')");
						}
					}
				}
				setColRuleList.add("setRuleColVal('"+colName+"','"+dropType+"','"+colRuleName+"','"+colType+"',"+ruleColCount+")");
				colRuleList.add(colGeneMethodRule);
				ruleColCount++;
			}
		}
		
		net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(mapApplyColRule);
		mapApplyColRuleJsonStr=jsonObject.toString();
		net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(colRuleList);
		colRuleListJsonStr = jsonArray.toString();
		net.sf.json.JSONArray jsonArray1 = net.sf.json.JSONArray.fromObject(setColRuleList);
		setColRuleListJsonStr = jsonArray1.toString();
	}
	System.out.println("  End apply_gene_rule:"+new java.util.Date());
%>


<%if(isAddOrEdit==true) {%>
<script type="text/javascript" src="avicit/cbb/techclass/tabledefine/commtablemanager/custom_function.js"></script>
<script type="text/javascript">
	//要组合项规则中包含的列的集合，用于在字段控件的change中获取并执行
	var applyColRule = <%=mapApplyColRuleJsonStr%>
	//组合项规则列表
	var colRuleList = <%=colRuleListJsonStr%>
	//要设置字段列表
	var setColRuleList = <%=setColRuleListJsonStr%>
	//应用组合项规则
	function applyRule(){
		//文件框
		$(".table_init td input").change(function(){
			var currId = this.id;
			var setColRuleIndex = applyColRule[currId];
			if(typeof setColRuleIndex!="undefined"){
				for(var i=0,len=setColRuleIndex.length;i<len;i++){
					var currSetColRule = setColRuleList[setColRuleIndex[i]];
					eval(currSetColRule);
				}
			}
		});
		//add by zhangjq 2020-5-3 13:58 设置没有其他字段生成的时候的处理，比如规则为year() -1
		<%if(dialogId!=null && dialogId.contains("Add")){%>
		$(".table_init td input").each(function(){
			var currId = this.id;
			var setColRuleIndex = applyColRule[currId];
			if(typeof setColRuleIndex!="undefined"){
				for(var i=0,len=setColRuleIndex.length;i<len;i++){
					var currSetColRule = setColRuleList[setColRuleIndex[i]];
					eval(currSetColRule);
				}
			}
		});
		<%}%>
		//end add
		//日期框
		$(".table_init td .easyui-datebox").each(function(){
			$(this).datebox({
				onSelect:function(date){
					var currId = this.id;
					var setColRuleIndex = applyColRule[currId];
					if(typeof setColRuleIndex!="undefined"){
						for(var i=0,len=setColRuleIndex.length;i<len;i++){
							var currSetColRule = setColRuleList[setColRuleIndex[i]];
							eval(currSetColRule);
						}
					}
				}
			});
		});
		//下拉框
		$(".table_init td select").each(function(){
			$(this).combobox({
				onSelect:function(rec){
					var currId = this.id;
					var setColRuleIndex = applyColRule[currId];
					if(typeof setColRuleIndex!="undefined"){
						for(var i=0,len=setColRuleIndex.length;i<len;i++){
							var currSetColRule = setColRuleList[setColRuleIndex[i]];
							eval(currSetColRule);
						}
					}
				}
			});
		});
		//选择框
		$(".table_init td .selector-div-input").each(function(){
			this.valueChanged=function(sender){
				var currId = sender.id;
				var setColRuleIndex = applyColRule[currId];
				if(typeof setColRuleIndex!="undefined"){
					for(var i=0,len=setColRuleIndex.length;i<len;i++){
						var currSetColRule = setColRuleList[setColRuleIndex[i]];
						eval(currSetColRule);
					}
				}
			};
			setSelectorChangedEvent(this);
		});

		 /* for(var i=0,len=setColRuleList.length;i<len;i++){
			eval(setColRuleList[i]);
		}  */
	}
	$(function(){
		setTimeout(function(){
			applyRule();
		},500);
	});
	
	//获取组合项中字段
	function getColVal(colName, dropType, ruleType, colType){
		if(dropType=="0" || dropType==""){
			if(colType=="date"){
				return $("#"+colName).datebox('getValue');
			}else{
				return $("#"+colName).val();
			}
		}else if(dropType=="1" || dropType=="2"){
			var val = $("#"+colName).combobox("getValue");
			if(val==""){
				return "";
			}else{
				// return $("#"+colName).combobox("getText");
				return val;  //保管期限生成档号需要获取下拉框真实值
			}
		}else if(dropType=="3" || dropType=="4"){//是选择框
			return $("#"+colName).val();
		}
		return "";
	}
	
	//设置应用了组合项生成的字段值
	function setRuleColVal(colName, dropType, ruleType, colType, ruleIndex){
		var currColRule = colRuleList[ruleIndex];
		var applyRuleResult = eval(currColRule);
		if(dropType=="0" || dropType==""){
			$("#"+colName).val(applyRuleResult);
		}
	}
	
	//设置选择框值改变事件，如选人和选单位
	function setSelectorChangedEvent(sender){
		setTimeout(function(){
			if(sender.value!="" && sender.value!=sender.oldValue){
				sender.oldValue=sender.value;
				if(typeof sender.valueChanged=="function"){
					sender.valueChanged(sender);
				}
			}
			setSelectorChangedEvent(sender);
		},1000);
	}
	
<%-- 	//获取组合项中案卷字段值
	function getAjColVal(archivesId, colId, colName, dropType, ruleType, colType){
		if(archivesId==""){//案卷级id为空时，返回空
			return "";
		}
		var ajTableName='<%=ajTableName%>';
		if(ajTableName==""){
			return "";
		}
		var rsVal="";
		var conId = "#"+colId;
		//存在控件时直接获取值
		if($(conId).length>0){
			rsVal = $(conId).val();
		}else{//不存在时，从后台读取数据
			$.ajax({
				url:"platform/sysstandardfunction/SysStandardFunctionController/getAjColValue",
				data:{id:colId,colName:colName,tableName:ajTableName,archivesId:archivesId},
				type:"post",
				async:false,
				success:function(colVal){
					rsVal=colVal;
				}
			});
		}
		return rsVal;
	} --%>
</script>
<%}%>